package io.dy.controller;

import io.dy.anno.RateLimiter;
import io.dy.enums.LimitType;
import io.dy.service.IRedisService;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;

/**
 * @author : dmj
 * @date: 2024/6/25 4:00 下午
 * @description:
 */
@RestController
@RequestMapping("/dy/login")
@RequiredArgsConstructor
public class LoginController {

    private final StringRedisTemplate stringRedisTemplate;

    private final IRedisService redisService;


    @PostMapping
    @RateLimiter(count = 10, limitType = LimitType.IP)
    public String login(@RequestParam("username") String username, @RequestParam("password") String password){
        System.out.println("用户为:" + username + ",密码为:" + password);
        return "success";
    }

    @GetMapping
    public Long test(){
        DefaultRedisScript<Long> limitScript = new DefaultRedisScript<>();
        limitScript.setLocation(new ClassPathResource("lua/test.lua"));
        limitScript.setResultType(Long.class);
        Long result = stringRedisTemplate.execute(limitScript, Collections.singletonList("key"), "10", "60");
        System.out.println("结果为:" + result);
        return result;
    }

    @GetMapping("/incr")
    public Long testIncr(String key){
        return redisService.incr(key);
    }

    @GetMapping("/set")
    public void set() throws InterruptedException {
        redisService.set();
    }
}
